import { Component, OnInit, OnDestroy, EventEmitter } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { Subject } from "rxjs/Subject";
import { Subscription } from "rxjs/Subscription";
import { StockBusiness } from "./stock-business-replay";
import { Headers } from "@angular/http";
import { CmHttp } from "http-module";
import { UserToken, DEFAULT_VERIFY, OPERATE_BUY, OPERATE_SELL } from "vtrade";
import { BASEURL } from "shared";
import { HsOpenUrl } from "./../hs-client.service";

const TABLE_HEADERS = [
  {
    "label": "证券名称",
    "key": "stock_name"
  },
  {
    "label": "证券代码",
    "key": "stock_code"
  },
  {
    "label": "现价",
    "key": "last_price"
  },
  {
    "label": "成本",
    "key": "cost_price"
  },
  {
    "label": "持有数量",
    "key": "current_amount"
  },
  {
    "label": "可卖数量",
    "key": "enable_amount"
  },
  {
    "label": "最新市值",
    "key": "market_value"
  },
  {
    "label": "盈亏比例",
    "key": "income_radio",
    "classes": ["with-percent"]
  },
  {
    "label": "盈亏金额",
    "key": "income_balance"
  }
];

const TAB_LIST = [
  {
    "text": "持仓单"
  }
];

@Component({
  // moduleId: module.id,
  selector: "stock-business",
  templateUrl: "stock-business.component.html",
  styleUrls: [
    "stock-business.component.less"
  ],
  inputs: [
    "updateSource"
  ],
  outputs: [
    "positionClick"
  ]
})
export class StockBusinessComponent implements OnInit, OnDestroy {
  mainSubscription: Subscription;
  tableHeaders = TABLE_HEADERS;
  listData = TAB_LIST;
  updateSource: Subject<any>;
  dataSource: Observable<StockBusiness[]>;
  dataList: StockBusiness[];
  positionClick = new EventEmitter();

  constructor(private http: CmHttp) { }

  ngOnInit() {
    !this.updateSource ? this.updateSource = new Subject() : null;
    console.debug("StockPosition UpdateSource: ", this.updateSource);
    this.dataSource =
      this.updateSource
        .switchMap(() =>
          this.http.get(
            `${BASEURL}/simtrades/me`, {
              withCredentials: true
            })
            .switchMap((res: UserToken) =>
              this.http.post(`${HsOpenUrl}/secu/v1/stockposition_qry`, DEFAULT_VERIFY, {
                headers: new Headers({
                  Authorization: `Bearer ${res.token}`
                }),
              })
            )
        )
        .map(body =>
          body.data
            .map((stock: StockBusiness) =>
              Object.assign(
                {}, stock, { income_radio: ((stock.last_price - stock.cost_price) / stock.cost_price * 100).toFixed(2) }
              )
            )
        );
    this.mainSubscription = this.dataSource.subscribe(
      res => this.dataList = res,
      err => this.dataList = []
    );
    this.updateSource.next({});
  }

  ngOnDestroy() {
    if (this.mainSubscription) {
      this.mainSubscription.unsubscribe();
    }
  }

  trackBySymbol(symbol: StockBusiness) {
    return symbol.stock_code;
  }

  handleOperate(entry: StockBusiness, isSell?: boolean) {
    console.debug("Stock Position Emit: ", entry, " isSell: ", isSell);
    this.positionClick.next({
      stock: entry,
      isSell
    });
  }

  getEntryClass(entry: StockBusiness) {
    return {
      "color-red": entry.income_balance >= 0,
      "color-green": entry.income_balance < 0
    };
  }

}